/**
 * 修改手机或绑定手机
 */
package org.morningangel.servlet.android;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.morningangel.bean.User;
import org.morningangel.dao.UserDao;
import org.morningangel.dao.impl.UserDaoImpl;
import org.morningangel.util.EncryptUtil;

@WebServlet(name = "AndroidUpdatePhoneServlet", urlPatterns = "/android/updatePhone")
public class UpdatePhoneServlet extends HttpServlet {
	private static final long serialVersionUID = 7149007631626265393L;

		public void doGet(HttpServletRequest request, HttpServletResponse response)
				throws ServletException, IOException {
			doPost(request, response);
		}

		public void doPost(HttpServletRequest request, HttpServletResponse response)
				throws ServletException, IOException {

			request.setCharacterEncoding("utf-8");
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
		    Integer userId  = Integer.parseInt(request.getParameter("userId"));
			String telNum = request.getParameter("telNum");
			String password = request.getParameter("password");
			UserDao userDao = new UserDaoImpl();
			User user = userDao.login(telNum);
			Integer status = 0;
			if (userId == 0) {
				//找回密码
				if (user != null) {
					//用户存在
					user.setPassword(EncryptUtil.md5(password));
					userDao.update(user);
					status = 1;
				}
			} else {
				//绑定手机
				if (user == null) {
					//手机号可用
					user = userDao.getById(userId);
					user.setPhone(telNum);
					userDao.update(user);
					status = 1;
				}
			}	
			PrintWriter out = response.getWriter();
			out.print("{\"isSuccess\":\"" + status + "\"}");
			out.flush();
			out.close();
		}


}
